package cn.myapps.msg.listener;

import cn.myapps.msg.sender.IMsgSender;
import cn.myapps.msg.sender.MsgSenderFactory;
import cn.myapps.msg.vo.MsgCommon;
import cn.myapps.msg.vo.SendResult;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;

/**
 * 消息发送监听器
 * 从MQ获取消息并发送
 */
@Component
@Slf4j
public class MsgSendListener {

    @JmsListener(destination = "my.msg.queue.${activemq.queue.env}", containerFactory = "jmsListenerContainerQueue")
    private void handleQueue(final String json) {
        log.info("开始处理消息 -> " + json);

        MsgCommon commonMsg = JSON.parseObject(json, MsgCommon.class);
        IMsgSender sender = MsgSenderFactory.getMsgSender(commonMsg.getMsgType());
        SendResult result = null;
        if (commonMsg.isSendByTemplate()) {
            result = sender.sendByTemplate(commonMsg);
        } else {
            result = sender.send(commonMsg);
        }

        log.info("处理消息成功, 结果: {}", result.isSuccess());
    }

    @JmsListener(destination = "my.msg.topic.${activemq.queue.env}", containerFactory = "jmsListenerContainerTopic")
    private void handleTopic(final String json) {
        log.info("开始处理订阅消息 -> " + json);

        MsgCommon commonMsg = JSON.parseObject(json, MsgCommon.class);
        IMsgSender sender = MsgSenderFactory.getMsgSender(commonMsg.getMsgType());
        SendResult result = null;
        if (commonMsg.isSendByTemplate()) {
            result = sender.sendByTemplate(commonMsg);
        } else {
            result = sender.send(commonMsg);
        }

        log.info("处理订阅消息成功, 结果: {}", result.isSuccess());
    }
}
